/**
 *
 *
 *
 *
 *
 */

package org.sxp.modules.sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.sxp.common.exception.BusinessException;
import org.sxp.common.jwt.JwtFilter;
import org.sxp.common.jwt.JwtUtlis;
import org.sxp.common.web.WrapperResponse;
import org.sxp.modules.sys.entity.SysUserEntity;
import org.sxp.modules.sys.service.SysUserService;
import org.sxp.modules.sys.shiro.ShiroUtils;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录相关
 *
 *
 */
@Controller
@Api(description="User", tags = "系统登录")
@ConditionalOnProperty(prefix = "shiro", name = "type", havingValue = "jwt")
public class SysLoginJWTController {
	@Autowired
	private Producer producer;

	@Autowired
	private SysUserService userService;

//	@Value("${server.servlet.session.cookie.domain}")
//	private String domainId;
	
	@RequestMapping(value = "captcha.jpg",method = RequestMethod.GET)
	public void captcha(HttpServletResponse response)throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);
        
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
	}

	@RequestMapping(value = "captchaSwagger.jpg",method = RequestMethod.GET)
	@ApiOperation(value = "验证码")
	public void captchaSwagger(HttpServletResponse response)throws Exception {
		//生成文字验证码
		String text = producer.createText();
		Map params = new HashMap();
		params.put("captchaToken", text);
		String token = JwtUtlis.getToken(params);
		response.addHeader("captchaToken", token);
		//生成图片验证码
		BufferedImage image = producer.createImage(text);
		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
	}

	/**
	 * jwt登录
	 */
	@ResponseBody
	@RequestMapping(value = "/sys/login", method = RequestMethod.POST)
	@ApiOperation(value = "JWT登录")
	public WrapperResponse loginJwt(String username, String password, String captcha,String captchaToken, HttpServletResponse response) {
//		String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
//		if(StringUtils.isNotBlank(captchaToken)){
//			kaptcha = ;
//		}
		if(!captcha.equalsIgnoreCase(JwtUtlis.getString(captchaToken, "captchaToken"))){
			throw new BusinessException("验证码不正确");
		}

		try{
			SysUserEntity userEntity = userService.getOne(
					new LambdaQueryWrapper<SysUserEntity>()
					.eq(SysUserEntity::getUsername, username)
			);
			if(userEntity == null){
				throw new UnknownAccountException();
			}
			password = ShiroUtils.sha256(password, userEntity.getSalt());
			if(!password.equals(userEntity.getPassword())){
				throw new IncorrectCredentialsException();
			}

			if(userEntity.getStatus() == 0){
				throw new LockedAccountException();
			}
			Map<String,String> params = new HashMap<>();
			params.put("userId", userEntity.getUserId().toString());
			params.put("username", userEntity.getUsername());
			String token = JwtUtlis.getToken(params);
			response.setHeader(JwtFilter.JWT_TOKEN_KEY, token);
			Cookie cookie = new Cookie(JwtFilter.JWT_TOKEN_KEY, token);
//			cookie.setDomain(domainId);
			cookie.setPath("/");
			cookie.setMaxAge(-1);
			cookie.setHttpOnly(true);
			response.addCookie(cookie);
			return WrapperResponse.success(token);
		}catch (UnknownAccountException e) {
			throw new BusinessException("账号不存在");
		}catch (IncorrectCredentialsException e) {
			throw new BusinessException("账号或密码不正确");
		}catch (LockedAccountException e) {
			throw new BusinessException("账号已被锁定,请联系管理员");
		}catch (AuthenticationException e) {
			throw new BusinessException("账户验证失败");
		}catch (Exception ex){
			ex.printStackTrace();
		}

		return WrapperResponse.fail(null);
	}
	
	/**
	 * 退出
	 */
	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public String logout() {
		ShiroUtils.logout();
		return "redirect:login.html";
	}
	
}
